package Arrays;

/**
 * 作者:hfj
 * 功能:最长公共前缀
 * 日期: 2025/10/14 20:46
 */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        String strs[] = {"flowers","flo","fl"};
        System.out.println(longestCommonPrefix(strs));
    }


    public static String longestCommonPrefix(String[] strs) {

        //1.先判空
        if (strs == null || strs.length == 0){
            return "";
        }

        //2.取出第一个字符串的每种可能性
        String[] strings = new String[strs[0].length()];
        for (int i = 0; i < strings.length; i++) {
            strings[i] = strs[0].substring(0,i+1);
        }

        String result = "";
        for (int i = 0; i < strings.length; i++) {
            String val = strings[i];
            boolean isVal = true;
            for (int j = 0; j < strs.length; j++) {
                //如果后面的字符串长度小于当前字符串则匹配到最大值
                if (strs[j].length() < val.length()){
                    isVal = false;
                    break;
                }

                String target = strs[j].substring(0, val.length());
                if (!target.equals(val)){
                    isVal = false;
                    break;
                }
            }

            //处理结果
            if (!isVal){
                break;
            }else {
                result = val;
            }
        }

        return result;
    }
}
